import router from '@system.router';
import prompt from '@system.prompt';
import http from '@ohos.net.http';
import dataStorage from '@ohos.data.storage'
import mockData from '../mock/mockData.js';
// 后台接口请求前缀
const BASE_URL = "http://119.29.77.218:8080/edu-platform/background"
const RESULT_SUCCESS = 20000;
const RESULT_LOGIN_FAIL = 50001;
const RESULT_TOKEN_FAIL = 50014;

const NO_TOKEN_REQUEST_URL = ['/api/studentLogin', '/api/getCourses', '/api/getHotCourses', '/api/getClasses', '/api/getHotClasses'];
const MOCK_MODE = true;
var token;

export default {
    get(params) {
        this.sendRequest('GET', params);
    },
    post(params) {
        this.sendRequest('POST', params);
    },
    setHttpRequestOptions(method, token, params) {
        let options = {
            method: method, // 可选，默认为“GET”
            header: {
                'Content-Type': 'application/json',
                'token': token
            },
            // 当使用POST请求时此字段用于传递内容
            extraData: params.data,
            readTimeout: 60000, // 可选，默认为60000ms
            connectTimeout: 60000 // 可选，默认为60000ms
        };
        return options;
    },
    sendRequest(method, params) {
        let that = this;

        // 填写http请求的url地址，可以带参数也可以不带参数。URL地址需要开发者自定义。GET请求的参数可以在extraData中指定
        let url = BASE_URL + params.uri;

        // 设置 Http Request 的选项信息，并在请求 header 中，增加 token 认证信息,
        let token = getApp().globalData.token;
        console.info('HttpUtil Token :' + token);

        let options = this.setHttpRequestOptions(method, token, params);
        console.info('setHttpRequestOptions:' + JSON.stringify(options));
        if(params.dialog!=null){
            params.dialog.show();
        }
        // 每一个httpRequest对应一个http请求任务，不可复用F
        http.createHttp().request(url, options, (err, data) => {
            if(params.dialog!=null){
                params.dialog.close();
            }
            if (!err) {
                // data.result为http响应内容，可根据业务需要进行解析
                console.info('code:' + data.responseCode);
                if (200 == data.responseCode) {
                    console.info('result:' + data.result);
                    let apiResult = JSON.parse(data.result);
                    if (apiResult.code == RESULT_SUCCESS) {
                        params.success(apiResult.data);
                    } else if (apiResult.code == RESULT_TOKEN_FAIL) {
                        router.replace({
                            uri: 'pages/login/login',
                            history: ''
                        })
                        that.showToast(apiResult.msg);
                    } else {
                        that.showToast(apiResult.msg);
                    }
                } else {
                    if(MOCK_MODE){
                        params.success(mockData.mock(params.uri+' '+method,params.data));
                    }else{
                        that.showToast("网络异常，请联系管理员");
                    }
                }
                /*    router.push({
                            uri: 'pages/login/login',
                            history: ''
                        })*/
            } else {
                console.info('error:' + err.data);
                if (MOCK_MODE) {
                    params.success(mockData.mock(params.uri + ' ' + method, params.data));
                } else {
                    that.showToast("未知异常，请联系管理员")
                }
            }
        });
    },
    setToken(token) {
        let path = getApp().globalData.path;
        let storage = dataStorage.getStorageSync(path);
        storage.putSync('token', token);
        storage.flushSync();
    },
    checkNoTokenRequestUrl(url) {
        let flag = false;
        for (let i in NO_TOKEN_REQUEST_URL) {
            if (url == NO_TOKEN_REQUEST_URL[i]) {
                flag = true;
            }
        }
        return flag;
    },
    showToast(msg) {
        prompt.showToast({
            message: msg
        })
    },
    forward() {
        router.push({
            uri: 'pages/login/login',
            history: ''
        })
    }
}

